const express = require('express');
const router = express.Router();
const Order = require('../models/Order');
const Tour = require('../models/Tour');
const Hotel = require('../models/Hotel');

// 简化的认证中间件 - 用于演示
const simpleAuth = (req, res, next) => {
  // 简化版：直接使用固定的用户ID用于演示
  req.user = {
    userId: '6872826501b094a9bfe8e055' // 测试用户ID
  };
  next();
};

// ==================== 订单创建 API ====================

// 创建旅游攻略订单
router.post('/tours', simpleAuth, async (req, res) => {
  try {
    const {
      tourId,
      startDate,
      endDate,
      quantity = 1,
      customerInfo,
      specialRequests = []
    } = req.body;

    // 验证旅游产品
    const tour = await Tour.findById(tourId);
    if (!tour) {
      return res.status(404).json({
        success: false,
        message: '旅游产品不存在'
      });
    }

    // 计算价格
    const unitPrice = tour.price;
    const totalPrice = unitPrice * quantity;

    // 生成订单号
    const orderNumber = Order.generateOrderNumber();

    // 创建订单
    const order = new Order({
      orderNumber,
      userId: req.user.userId,
      productType: 'tour',
      productId: tourId,
      productSnapshot: {
        title: tour.title,
        subtitle: tour.subtitle,
        image: tour.image,
        category: tour.category,
        destination: tour.destination,
        duration: tour.duration,
        description: tour.description,
        highlights: tour.highlights
      },
      quantity,
      unitPrice,
      totalPrice,
      startDate: new Date(startDate),
      endDate: new Date(endDate),
      customerInfo,
      specialRequests
    });

    await order.save();

    // 更新产品预订统计
    await Tour.findByIdAndUpdate(tourId, {
      $inc: { 
        soldCount: quantity
      }
    });

    res.status(201).json({
      success: true,
      message: '旅游订单创建成功',
      data: order
    });

  } catch (error) {
    console.error('创建旅游订单失败:', error);
    res.status(500).json({
      success: false,
      message: '创建订单失败',
      error: error.message
    });
  }
});

// 创建酒店预订订单
router.post('/hotels', simpleAuth, async (req, res) => {
  try {
    const {
      hotelId,
      checkInDate,
      checkOutDate,
      roomCount = 1,
      customerInfo,
      specialRequests = []
    } = req.body;

    // 验证酒店
    const hotel = await Hotel.findById(hotelId);
    if (!hotel) {
      return res.status(404).json({
        success: false,
        message: '酒店不存在'
      });
    }

    // 计算住宿天数
    const checkIn = new Date(checkInDate);
    const checkOut = new Date(checkOutDate);
    const nights = Math.ceil((checkOut - checkIn) / (1000 * 60 * 60 * 24));
    
    // 计算价格
    const unitPrice = hotel.price;
    const totalPrice = unitPrice * roomCount * nights;

    // 生成订单号
    const orderNumber = Order.generateOrderNumber();

    // 创建订单
    const order = new Order({
      orderNumber,
      userId: req.user.userId,
      productType: 'hotel',
      productId: hotelId,
      productSnapshot: {
        name: hotel.name,
        description: hotel.description,
        address: hotel.address,
        city: hotel.city,
        mainImage: hotel.mainImage,
        starRating: hotel.starRating,
        amenities: hotel.amenities
      },
      quantity: roomCount,
      unitPrice,
      totalPrice,
      startDate: checkIn,
      endDate: checkOut,
      customerInfo,
      specialRequests
    });

    await order.save();

    // 更新酒店预订统计
    await Hotel.findByIdAndUpdate(hotelId, {
      $inc: { 
        bookingCount: 1
      }
    });

    res.status(201).json({
      success: true,
      message: '酒店订单创建成功',
      data: order
    });

  } catch (error) {
    console.error('创建酒店订单失败:', error);
    res.status(500).json({
      success: false,
      message: '创建订单失败',
      error: error.message
    });
  }
});

// ==================== 订单查询 API ====================

// 获取用户所有订单
router.get('/', simpleAuth, async (req, res) => {
  try {
    const {
      page = 1,
      limit = 10,
      status,
      productType
    } = req.query;

    const query = { userId: req.user.userId };
    
    if (status) query.status = status;
    if (productType) query.productType = productType;

    // 分页参数
    const pageNum = parseInt(page);
    const limitNum = parseInt(limit);
    const skip = (pageNum - 1) * limitNum;

    const orders = await Order.find(query)
      .sort({ createdAt: -1 })
      .skip(skip)
      .limit(limitNum);

    const total = await Order.countDocuments(query);

    res.json({
      success: true,
      data: orders,
      pagination: {
        page: pageNum,
        limit: limitNum,
        total,
        pages: Math.ceil(total / limitNum)
      }
    });

  } catch (error) {
    console.error('获取订单列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取订单失败',
      error: error.message
    });
  }
});

// 获取订单详情
router.get('/:orderId', simpleAuth, async (req, res) => {
  try {
    const { orderId } = req.params;
    
    const order = await Order.findOne({
      _id: orderId,
      userId: req.user.userId
    });

    if (!order) {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }

    res.json({
      success: true,
      data: order
    });

  } catch (error) {
    console.error('获取订单详情失败:', error);
    res.status(500).json({
      success: false,
      message: '获取订单详情失败',
      error: error.message
    });
  }
});

// ==================== 订单管理 API ====================

// 取消订单
router.patch('/:orderId/cancel', simpleAuth, async (req, res) => {
  try {
    const { orderId } = req.params;
    const { cancellationReason = '用户主动取消' } = req.body;

    const order = await Order.findOne({
      _id: orderId,
      userId: req.user.userId
    });

    if (!order) {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }

    if (order.status === 'cancelled') {
      return res.status(400).json({
        success: false,
        message: '订单已经取消'
      });
    }

    // 更新订单状态
    order.status = 'cancelled';
    order.cancellationReason = cancellationReason;
    await order.save();

    res.json({
      success: true,
      message: '订单取消成功',
      data: order
    });

  } catch (error) {
    console.error('取消订单失败:', error);
    res.status(500).json({
      success: false,
      message: '取消订单失败',
      error: error.message
    });
  }
});

// 删除订单
router.delete('/:orderId', simpleAuth, async (req, res) => {
  try {
    const { orderId } = req.params;

    const order = await Order.findOne({
      _id: orderId,
      userId: req.user.userId
    });

    if (!order) {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }

    // 只有已取消或已完成的订单可以删除
    if (!['cancelled', 'completed'].includes(order.status)) {
      return res.status(400).json({
        success: false,
        message: '只能删除已取消或已完成的订单'
      });
    }

    await Order.findByIdAndDelete(orderId);

    res.json({
      success: true,
      message: '订单删除成功'
    });

  } catch (error) {
    console.error('删除订单失败:', error);
    res.status(500).json({
      success: false,
      message: '删除订单失败',
      error: error.message
    });
  }
});

module.exports = router; 